<template>
  <div style="height: 100%">
    <div class="table-box table-content">
      <ProTable
        ref="proTable"
        :columns="columns"
        :request-api="getUpgradeLevelList"
        :init-param="initParam"
        :request-auto="true"
        :data-callback="dataCallback"
        :search-col="{ xs: 1, sm: 1, md: 1, lg: 1, xl: 1 }"
        row-key="ulId"
      >
        <!-- @row-click="showCustomFieldList" -->
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button type="primary" :icon="CirclePlus" @click="addUL">新增</el-button>
          <el-button type="primary" :icon="EditPen" plain @click="editUL(scope)">编辑</el-button>
          <el-button type="primary" :icon="Delete" plain @click="delUL(scope)">删除</el-button>
          <!-- <el-button type="primary" :icon="Search" plain @click="search(scope)">搜索</el-button> -->
        </template>
      </ProTable>

      <el-drawer v-model="drawer" :title="`${title}升级级别`" :direction="direction" :before-close="handleClose">
        <el-form>
          <el-form-item label="级别">
            <el-input v-model="levelName" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="升级到">
            <el-input v-model="userName" placeholder="请输入内容" @click="getUser" />
          </el-form-item>
          <el-form-item label="操作">
            <el-button type="primary" :icon="Upload" @click="UploadGroup">提交</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>
      <el-dialog v-model="dialogVisible" title="选择用户" width="80%" :before-close="handleClose_getUser">
        <div class="main-box">
          <TreeFilter
            label="data"
            id="attr"
            title="部门列表"
            :data="treeFilterData"
            :default-value="treeInitParam.departmentId"
            @change="changeTreeFilter"
          />
          <div style="height: auto" class="table-box">
            <ProTable
              ref="useProTable"
              :columns="userColumns"
              :request-api="getUserTreeList"
              :init-param="treeInitParam"
              :request-auto="true"
              :data-callback="dataCallback"
              :search-col="{ xs: 1, sm: 1, md: 1, lg: 1, xl: 1 }"
            >
              <template #operation="scope">
                <el-button type="primary" :icon="Select" @click="chooseUser(scope)">选择</el-button>
              </template>
            </ProTable>
          </div>
        </div>
        <!-- <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="dialogVisible = false">确认</el-button>
          </span>
        </template> -->
      </el-dialog>
    </div>
  </div>
</template>
<script setup lang="ts" name="upgradationLevel">
import { ref, reactive, onMounted } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import {
  getUpgradeLevelList,
  checkUpgradeLevel,
  addUpgradeLevel,
  delUpdateLevel,
  checkUpgradeLevelEdit,
  editUpgradeLevel
} from "@/api/modules/dataDictionary";
import { CirclePlus, Delete, EditPen, Upload, Select } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import type { DrawerProps } from "element-plus";
import TreeFilter from "@/components/TreeFilter/treeFilter.vue";
import { getUserDepartment, getUserTreeList } from "@/api/modules/user";
const columns = reactive<ColumnProps<any>[]>([
  { type: "selection" },
  {
    prop: "ulName",
    label: "级别名称",
    sortable: true,
    search: {
      el: "input",
      tooltip: "输入级别名称",
      label: "输入名称",
      key: "updateLevelQueryDTO.ulName"
    }
  },
  {
    prop: "approvalName",
    label: "升级到",
    sortable: true
  }
]);
const userColumns = reactive<ColumnProps<any>[]>([
  { type: "selection" },
  {
    prop: "loginName",
    label: "登录名",
    sortable: true,
    search: {
      el: "input",
      tooltip: "输入级别名称",
      label: "输入名称",
      key: "updateLevelQueryDTO.ulName"
    }
  },
  {
    prop: "fullName",
    label: "名字",
    sortable: true
  },
  {
    prop: "email",
    label: "邮件",
    sortable: true
  },
  {
    prop: "holidayStatus",
    label: "休假状态",
    sortable: true,
    render: (scope: any) => {
      switch (scope.row.holidayStatus) {
        case true:
          return "休假";
        case false:
          return "值班中";
        default:
          return "";
      }
    }
  },
  { prop: "operation", label: "操作" }
]);
const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};
//初始化参数
const proTable = ref<ProTableInstance>();
const initParam = ref("");
const drawer = ref(false);
const direction = ref<DrawerProps["direction"]>("rtl");
const dialogVisible = ref(false);
const handleClose = () => {
  drawer.value = false;
};
const levelName = ref("");
const userName = ref("");
const title = ref("");
const treeFilterData = ref<any>([]);
const treeInitParam = reactive({
  departmentId: ""
});
const userId = ref("");
//新增
const addUL = () => {
  title.value = "新增";
  drawer.value = true;
};
//弹出框操作
const handleClose_getUser = (done: () => void) => {
  ElMessageBox.confirm("确定退出吗?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
//选择用户
const chooseUser = e => {
  console.log(e);
  userName.value = e.row.fullName;
  dialogVisible.value = false;
  userId.value = e.row.userId;
};
//获取用户
const getUser = async e => {
  console.log(e);
  dialogVisible.value = true;
  const data = await getUserDepartment();
  treeFilterData.value = data;
  treeInitParam.departmentId = treeFilterData.value[0].attr.orgNo;
};
//
const changeTreeFilter = (e: any) => {
  if ((e as any).id.orgNo === "1") {
    treeInitParam.departmentId = "";
  } else {
    treeInitParam.departmentId = (e as any).id.orgNo;
  }
};
//编辑
const ulId = ref("");
const editUL = e => {
  if (e.selectedList.length === 0 || e.selectedList.length > 1) {
    ElMessage.error("请选择一条数据");
  } else {
    title.value = "编辑";
    drawer.value = true;
    levelName.value = e.selectedList[0].ulName;
    userName.value = e.selectedList[0].approvalName;
    ulId.value = e.selectedList[0].ulId;
  }
};
//删除
const delUL = e => {
  if (e.selectedList.length === 0) {
    ElMessage.error("请选择至少一条数据");
  } else {
    let delStr = "";
    e.selectedList.forEach(item => {
      delStr += item.ulName + ",";
    });
    ElMessageBox.confirm("您确定要删除这些:" + delStr + "数据吗", "删除确认", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      center: true
    })
      .then(async () => {
        let params = "";
        e.selectedList.forEach(item => {
          params += "ulIds=" + item.ulId + "&";
        });
        try {
          const data = await delUpdateLevel(params);
          if ((data as any) === true) {
            ElMessage.success("删除成功");
            proTable.value?.clearSelection();
            proTable.value?.getTableList();
          }
        } catch {
          ElMessage.error("此数据存在相关联的数据，不能删除");
        }
        ElMessage({
          type: "success",
          message: "删除成功"
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除"
        });
      });
  }
};
//提交数据
const UploadGroup = async () => {
  if (title.value === "新增") {
    const checkParams = {
      "updateLevelDTO.ulName": levelName.value
    };
    const params = {
      "updateLevelDTO.ulName": levelName.value,
      "updateLevelDTO.approvalName": userName.value,
      "updateLevelDTO.approvalNo": userId.value,
      "updateLevelDTO.ulId": ""
    };
    const isAdd = await checkUpgradeLevel(checkParams);
    if ((isAdd as any) === "") {
      const data = await addUpgradeLevel(params);
      console.log(data);
      if ((data as any) === null) {
        ElMessage.success("新增成功");
        levelName.value = "";
        userName.value = "";
        userId.value = "";
        drawer.value = false;
        proTable.value?.getTableList();
      }
    } else {
      ElMessage.error("该升级级别已存在");
      return;
    }
  } else if (title.value === "编辑") {
    const checkParams = {
      "updateLevelDTO.ulName": levelName.value,
      "updateLevelDTO.ulId": ulId.value
    };
    const params = {
      "updateLevelDTO.ulName": levelName.value,
      "updateLevelDTO.approvalName": userName.value,
      "updateLevelDTO.approvalNo": userId.value,
      "updateLevelDTO.ulId": ulId.value
    };
    const isAdd = await checkUpgradeLevelEdit(checkParams);
    if ((isAdd as any) === "") {
      const data = await editUpgradeLevel(params);
      console.log(data);
      if ((data as any) === null) {
        ElMessage.success("编辑成功");
        levelName.value = "";
        userName.value = "";
        userId.value = "";
        ulId.value = "";
        drawer.value = false;
        proTable.value?.getTableList();
      }
    } else {
      ElMessage.error("该升级级别已存在");
      return;
    }
  }
};
</script>
